<template>
    <div class="preview-container">
        <div ref="scaleRef" class="scale-container" @wheel.prevent="handleWheelScale($event)">
            <div ref="moveRef" class="move-container" @mousedown="handleMouseMove">
                <slot></slot>
            </div>
        </div>
        <div class="handle-container">
            <div>
                <!-- <img src="./img/full.png" @click="fullScreen()" /> -->
            </div>
            <div>
                <!-- <img src="./img/reset.png" @click="reset" /> -->
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { useFullscreen } from '@vueuse/core';

const props = defineProps({
    scale: {
        type: Number,
        default: 1,
    },
});
// 控制区域
const scaleRef = ref();
const moveRef = ref();
const scale = ref(props.scale);

// 鼠标滚轮缩放
const handleWheelScale = (event: any) => {
    // scale.value += event.wheelDelta / 1200;
    let scaleNum = scale.value
    scaleNum += event.wheelDelta / 1200;
    if (scaleNum > 1.5) {
        scale.value = 1.5
    } else if (scaleNum < 0.5) {
        scale.value = 0.5
    } else {
        scale.value = scaleNum
    }
};
// 鼠标拖拽移动
const handleMouseMove = (e: any) => {
    e.preventDefault();
    let el = moveRef.value;
    if (el) {
        let X = e.clientX - el.offsetLeft;
        let Y = e.clientY - el.offsetTop;
        const move = (e: MouseEvent) => {
            el.style.left = e.clientX - X + 'px';
            el.style.top = e.clientY - Y + 'px';
        };
        document.addEventListener('mousemove', move);
        document.addEventListener('mouseup', () => {
            document.removeEventListener('mousemove', move);
        });
    }
};
// 位置复原
const reset = () => {
    scale.value = props.scale;
    moveRef.value.style.left = 0;
    moveRef.value.style.top = 0;
    moveRef.value.style.transform = 'translate(0, 0)';
};
// 全屏幕显示
const { isFullscreen, toggle } = useFullscreen(scaleRef);
// const ratio = ref(0);

const fullScreen = () => {
    scale.value = 1;

    // 全屏居中显示
    moveRef.value.style.top = '50%';
    moveRef.value.style.left = '50%';
    moveRef.value.style.transform = 'translate(-50%, -50%)';
    // 全屏事件
    toggle();
};
watch(isFullscreen, (val) => {
    // 所有弹窗隐藏
    // 全屏/未全屏下
    if (!val) {
        reset();
    }
});
</script>

<style lang="scss" scoped>
.preview-container {
    position: relative;
    width: 100%;
    height: 100%;
    // background: url('./img/bg-scale.png');
    // background-size: 100% 100%;
    overflow: hidden;

    .scale-container {
        width: 100%;
        height: 100%;
        transform: scale(v-bind(scale));
    }

    .move-container {
        width: 100%;
        height: 100%;
        position: relative;
    }

    .handle-container {
        position: absolute;
        top: 0;
        right: 0;

        img {
            width: 42px;
            cursor: pointer;
        }
    }
}
</style>
